package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.adapter.SearchAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.SearchCircleAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.SearchHistoryAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.SearchPostAdapter;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.AddCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.SearchCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.SearchPostDateBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.SelectSearchDateBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemClickListener;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 08 月 27 日
 * 作者  Z2043 welbeing to hangzou com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 *
 * @desc 搜索
 */
public class SearchActivity extends Activity {
    private static final String TAG = "SearchActivity";
    @Bind(R.id.activity_search_iv_search)
    ImageView activitySearchIvSearch;
    @Bind(R.id.activity_search_et_search_content)
    EditText activitySearchEtSearchContent;
    @Bind(R.id.activity_search_tv_search)
    TextView activitySearchTvSearch;
    @Bind(R.id.activity_circle_rl_search)
    RelativeLayout activityCircleRlSearch;
    @Bind(R.id.activity_search_tv_cancel)
    TextView activitySearchTvCancel;
    @Bind(R.id.activity_search_xrecyclerView)
    RecyclerView activitySearchXrecyclerView;
    @Bind(R.id.activity_search_xrecyclerView_history)
    RecyclerView activitySearchXrecyclerViewHistory;
    @Bind(R.id.activity_search_tv_clear_record)
    TextView activitySearchTvClearRecord;
    @Bind(R.id.activity_search_rl_clear_record)
    RelativeLayout activitySearchRlClearRecord;


    @Bind(R.id.activity_search_tv_join)
    TextView activitySearchTvJoin;
    @Bind(R.id.activity_search_tv_circle_class)
    TextView activitySearchTvCircleClass;
    @Bind(R.id.activity_search_tv_circle_introduce)
    TextView activitySearchTvCircleIntroduce;
    @Bind(R.id.activity_search_iv_hangzhou_circle)
    ImageView activitySearchTvHangzhouCircle;
    @Bind(R.id.activity_search_recyclerView_03)
    RecyclerView activitySearchRecyclerView03;
    @Bind(R.id.activity_search_rl_01)
    RelativeLayout activitySearchRl01;
    @Bind(R.id.activity_search_ll_01)
    LinearLayout activitySearchLl01;


    @Bind(R.id.activity_search_recyclerview_02)
    RecyclerView activitySearchRecyclerView02;


    private String[] arr = new String[]{"备孕","时尚辣妈","美食分享","摄影","美妆","旅游达人","婆媳圈","饮食","同龄圈","孕妈期","穿搭"};

    private List<String > mlist = new ArrayList();

    @Bind(R.id.activity_search_ll_seach_content)
    LinearLayout activitySearchLlSeachContent;
    private SearchCircleAdapter searchCircleAdapter;
    private String seachContent;
    private SearchPostAdapter searchCircleAdapter1;
    private SearchAdapter searchAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
      //  initState();
        //Utils.setStatusTextColor(false, SearchActivity.this);


        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);


        activitySearchLl01.setVisibility(View.VISIBLE);
        activitySearchLlSeachContent.setVisibility(View.GONE);
        loadSelectSearchDate();
        activitySearchEtSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                activitySearchTvSearch.setText("");
               // activitySearchEtSearchContent.requestFocus();

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                activitySearchTvSearch.setText(s.toString());
               // activitySearchEtSearchContent.setText(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e(TAG,"afterTextChanged========");

            }
        });
        /**----------------搜素圈子----------------*/
        LinearLayoutManager layoutManager_04= new  LinearLayoutManager(this);
        layoutManager_04.setOrientation(LinearLayoutManager.VERTICAL);
        activitySearchRecyclerView02.setLayoutManager(layoutManager_04);
        /**----------------搜素帖子----------------*/
        LinearLayoutManager layoutManager_02= new  LinearLayoutManager(this);
        layoutManager_02.setOrientation(LinearLayoutManager.VERTICAL);
        activitySearchRecyclerView03.setLayoutManager(layoutManager_02);


        /**----------------热门搜索----------------*/
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        activitySearchXrecyclerView.setLayoutManager(layoutManager);

        LinearLayoutManager layoutManager_01 = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        activitySearchXrecyclerViewHistory.setLayoutManager(layoutManager_01);
        SearchHistoryAdapter searchHistoryAdapter =  new SearchHistoryAdapter();
        activitySearchXrecyclerViewHistory.setAdapter(searchHistoryAdapter);

     /*   LinearLayoutManager layoutManager_02 = new LinearLayoutManager(this);
        layoutManager_02.setOrientation(LinearLayoutManager.VERTICAL);
        activitySearchRecyclerView03.setLayoutManager(layoutManager_02);
        SearchResultsAdapter searchResultsAdapter =  new SearchResultsAdapter();
        activitySearchRecyclerView03.setAdapter(searchResultsAdapter);*/





    }
    /**
     * @DESC 热门搜索
     * */
    private void loadSelectSearchDate() {
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.Hosts_SEARCH)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                         Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final SelectSearchDateBean selectSearchDateBean =  gson.fromJson(parseNetworkResponse,SelectSearchDateBean.class);
                        if(selectSearchDateBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    //mlist
                                   List<String>  mcat = selectSearchDateBean.data.cat;
                                   List<String>  mposts = selectSearchDateBean.data.posts;
                                    mlist.addAll(mcat);
                                    mlist.addAll(mposts);

                                    searchAdapter = new SearchAdapter(mlist);
                                    activitySearchXrecyclerView.setAdapter(searchAdapter);
                                    searchAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                                        @Override
                                        public void onItemClick(View view) {
                                            int position =  activitySearchXrecyclerView.getChildAdapterPosition(view);
                                            String hots =  mlist.get(position);
                                            activitySearchTvSearch.setText(hots);
                                            // loadSelectSearchDate(hots);


                                        }
                                        @Override
                                        public void onItemFirstButtonClick(View v, int position) {
                                            String hots =  mlist.get(position);
                                            activitySearchTvSearch.setText(hots);
                                        }
                                    });

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SearchActivity.this,selectSearchDateBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }


    /**
     * @desc 添加关注圈子
     * */
    private void addCircle(String id) {
        SharedPreferences sp = MyApplication.getMcontext().getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.ADD_CIRCLE)
                .addParams("cat_id", id)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        //Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),"添加成功",Toast.LENGTH_SHORT).show();
                                    loadSearchCircleDate(seachContent);
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 取消
     * @param id*/
    private void cancel(String id) {
        SharedPreferences sp = MyApplication.getMcontext().getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CANCEL_JOIN)
                .addParams("cat_id",id)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        //Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),"已取消",Toast.LENGTH_SHORT).show();
                                    loadSearchCircleDate(seachContent);
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    @OnClick({ R.id.activity_search_tv_search, R.id.activity_circle_rl_search,
            R.id.activity_search_rl_clear_record,R.id.activity_search_tv_cancel,})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_search_tv_search:
                break;
            case R.id.activity_circle_rl_search:
                break;
            case R.id.activity_search_rl_clear_record:
                break;
            case R.id.activity_search_tv_cancel:
                seachContent = activitySearchTvSearch.getText().toString().trim();
                if(!TextUtils.isEmpty(seachContent)){
                    loadSearchCircleDate(seachContent);
                    loadSearchPostDate(seachContent);
                }else{
                    Toast.makeText(SearchActivity.this,"请输入搜索的内容",Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }
    /**
     * @desc 加载搜索帖子的接口
     * */
    private void loadSearchPostDate(String seachContent) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.SEARCH_POST_DATE)
                .addParams("cus_id", user_id)
                .addParams("keyword", seachContent)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                        Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final SearchPostDateBean searchPostDateBean = gson.fromJson(parseNetworkResponse,SearchPostDateBean.class);
                        if(searchPostDateBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    List<SearchPostDateBean.DataBean> mlist = searchPostDateBean.data;
                                    if(mlist != null){
                                        searchCircleAdapter1 = new SearchPostAdapter(mlist,SearchActivity.this);
                                        activitySearchRecyclerView03.setAdapter(searchCircleAdapter1);
                                        activitySearchLl01.setVisibility(View.GONE);
                                        activitySearchLlSeachContent.setVisibility(View.VISIBLE);
                                    }

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),searchPostDateBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 加载搜索圈子的接口
     * @param seachContent*/
    private void loadSearchCircleDate(String seachContent) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.SEACH_CICLER_DATE)
                .addParams("cus_id", user_id)
                .addParams("keyword", seachContent)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =  response.body().string();
                        // Log.e(TAG,"parseNetworkResponse========"+parseNetworkResponse);
                        Gson gson =  new Gson();
                        final SearchCircleBean searchCircleBean =gson.fromJson(parseNetworkResponse,SearchCircleBean.class);
                        if(searchCircleBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    final List<SearchCircleBean.DataBean> mlist = searchCircleBean.data;
                                    if(mlist != null){
                                        searchCircleAdapter = new SearchCircleAdapter(mlist,SearchActivity.this);
                                        activitySearchRecyclerView02.setAdapter(searchCircleAdapter);
                                        searchCircleAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                                            @Override
                                            public void onItemClick(View view) {
                                                int position = activitySearchRecyclerView02.getChildAdapterPosition(view);
                                                Intent intent = new Intent(SearchActivity.this,TrueCircleActivity.class);
                                                intent.putExtra("circle_id",mlist.get(position).id);
                                                intent.putExtra("circle_num",mlist.get(position).num);
                                                intent.putExtra("circle_name",mlist.get(position).cat_name);
                                                intent.putExtra("circle_state",mlist.get(position).state+"");
                                                intent.putExtra("circle_url",mlist.get(position).url);
                                                startActivity(intent);

                                                SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                                SharedPreferences.Editor edit = sp.edit();
                                                edit.putString("circle_id",mlist.get(position).id);
                                                edit.commit();

                                                activitySearchLl01.setVisibility(View.GONE);
                                                activitySearchLlSeachContent.setVisibility(View.VISIBLE);
                                            }

                                            @Override
                                            public void onItemFirstButtonClick(View v, int position) {
                                                String id =   mlist.get(position).id;
                                                int state =   mlist.get(position).state;
                                                if(state == 0){
                                                    addCircle(id);
                                                }else if(state == 1){
                                                    cancel(id);
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }else {
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SearchActivity.this,searchCircleBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

}
